package com.rc.evcharger.common.utils;

/**
 * Create by Yang on 2021/7/23
 */
public class ASCIIUtil {


    /**
     * 将字符串转成ASCII的Java方法
     *
     * @param value
     * @return
     */
    public static String stringToAscii(String value, int length) {
        //截取前length
        if (value.length() > length) {
            value = value.substring(0, length);
        }

        //不足补0
        if (length > value.length()) {
            for (int i = 0; i < length; i++) {
                if (value.length() == length) {
                    break;
                }
                value += "0";
            }
        }

        //返回十六进制
        return NumberUtil.bin2HexStr(value.getBytes());
    }

    /**
     * 将ASCII转成字符串的java方法
     *
     * @param value
     * @param length
     * @return
     */
    public static String asciiToString(String value, int length) {
        StringBuffer sb = new StringBuffer();
        String[] strs = value.split(" ");
        for (int i = 0; i < strs.length; i++) {
            sb.append(StringToHexUtil.convertHexToString(strs[i]));
        }
        return sb.toString().trim();
    }


    public static void main(String[] args) {
        String str = "Xl9KWmKxLJagX05uUohLMUrTdrg0JngQRmQimEY8dmzT3L1fpZRFy5Eu1F0CPMyq";
        //String s = NumberUtil.bin2HexStr(str.getBytes());
        String asciiResult = stringToAscii(str, str.length());
        System.out.println(asciiResult);
        System.out.println(NumberUtil.bin2HexStr(str.getBytes()));
        String stringResult = asciiToString("31 31 35 33 34 34 30 30 30 30 31 31 00 00", 30);
        System.out.println(stringResult);
        System.out.println(stringResult.length());

        String s = ASCIIUtil.stringToAscii("11531", 16);
        System.out.println(s);
    }
}
